<?php
namespace Addons\Redenvelopes\Controller\H5;

use Lib\Response;
use Addons\CustomerPortrait\Helper;
use Models\BaseModel as Model;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Services\JsSdk;

use Addons\QyWechat\Services\WxpayService;

use Addons\Redenvelopes\Helper as QyHelper;
use Addons\QyWechat\Helper as QyHelpers;
class Replys extends \BaseController
{
    public function index(){
        $corp_id = \Request::get('corp_id');
        $agent_id = \Request::get('agent_id');
        $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$corp_id]);
        $wid = $qyConfig->wid;
        // $replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid,'agent_id'=>$agent_id]);
        $replyConfig = QyHelpers::getInstance()->get_message_send_config($wid);
        $user = (new \Model('qy_envelopes'))->where(["corp_id"=>$corp_id,"status"=>1])->list_all();
        if($_GET['code']){
            $code = $_GET['code'];
            $app = QyWechatApi::getInstance()->get_qy_agent_app($corp_id,$replyConfig->agent_id,$replyConfig->secret);
            $accessToken = $app->access_token; 
            $token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
            $resArr = json_decode(curlGet($url),1);
            $jsSdkServe = new JsSdk($corp_id,$agent_id,$replyConfig->secret);
            $wxConfig = $jsSdkServe->getSignPackage();
            $agentConfig = $jsSdkServe->getSignPackage('','agent');
            $qyUser = (new Model('qy_user_list'))->find(['wid'=>$wid,'userid'=>$resArr['UserId']]);
            $im_url = Helper::getInstance()->get_http_server_name()."/images/5a74fcc7f25ea9275760a94d849e68e.jpg"; 
            $copyright = QyHelpers::copyright($wid);
            $this->assign("im_url", $im_url);
            $this->assign("corp_id", $corp_id);
            $this->assign("agent_id", $replyConfig->agent_id);
            $this->assign("wxConfig", $wxConfig);       
            $this->assign("copyright", $copyright);       
            $this->assign("agentConfig", $agentConfig);     
            $this->assign("wid", $wid);     
            $this->assign("userId", $qyUser->id);
            $this->assign('user',$user);
            $this->assign('count',count($user));
            return $this->show();
        }else{
            $redirect_uri = urlencode(Helper::getInstance()->get_http_server_name().'/Addons/Redenvelopes/H5/Replys/index.html?corp_id='.$corp_id.'&agent_id='.$replyConfig->agent_id);
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$corp_id.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
            \Redirect::to($url);
        }
    }

    public function send(){
        set_time_limit(0);
        setApi(); //发送红包时候判断不能为空
            $wid = (new Model("qy_envelopes"))->find($_POST["id"]);
            $user_status = (new Model("qy_envelopes_status"))->find(["wid"=>$wid->user_id]);
            $user_arr = json_decode($user_status->user_arr,1);
            $qx =  in_array($_POST["user_id"],$user_arr);
            if(!$qx){
                sendError('没有权限');
            }
            $ktime = strtotime(date("Y-m-d"),time());
            $jtime = strtotime(date("Y-m-d"),time())+3600*24;
            $user_money = json_decode($user_status->user_money,1);
            $is_user = array_key_exists($_POST["user_id"],$user_money);
            $fs_user_id = (new \Model('qy_envelopes_send'))->where(["fs_user_id"=>$_POST["user_id"],"ctime@<"=>$jtime,"ctime@>"=>$ktime])->list_all();
            foreach ($fs_user_id as $key => $value) {
                $monay += $value->price;
            }
            if($is_user){
                foreach ($user_money as $k => $v) {
                    if($k == $_POST["user_id"]){
                        $user_moneys = $v;
                    }
                }
            }
            if($monay+$_POST["price"] >= $user_moneys){
                sendError("您的额度不足");
            }
            if($_POST["radio"] == "" || $_POST["value"] == "" ){
                sendError('不能为空');
            }
            if(is_float($_POST["value"])){
                sendError('可抢红包人数不能是小数');
            } 
            if($_POST["price"] / $_POST["value"] < 0.3 ){
                sendError('您的金额与个数不符');
            }
            if($_POST["radio"] == 2){
                $radio = "拼手气红包";
            }else{
                $arrs = $this->getDivideNumber($_POST["price"],$_POST["value"]);
                for ($i=0; $i <count($arrs); $i++) { 
                    if($arrs[$i] != $arrs[0]){
                        sendError('您的金额与个数做不到平分功能');
                    }
                }
                $radio = "普通红包";
            }
            if($_POST["values"] == ""){
                $word = "恭喜发财，大吉大利";
            }else{
                $word = $_POST["values"];
            }
            $corp_id = \Request::get(1);
            $send = new Model("qy_envelopes_send");
            $send->price = $_POST["price"];
            $send->status = $radio;
            $send->number = $_POST["value"];
            $send->sy_number = $_POST["value"];
            $send->word = $word;
            $send->wid = $wid->user_id;
            $send->mb_id = $_POST["id"];
            $send->corp_id = $corp_id;
            $send->fs_user_id = $_POST["user_id"];
            $send->is_quan = $_POST["is_quan"];
            $send->ctime = strtotime(date("Y-m-d H:i:s"));
            $send->save();
        if($send->id){  //执行接口
            $corp_id = \Request::get(1);
            $agent_id = \Request::get(2);
            $id = $_POST["id"];
            $qy_send = (new Model('qy_envelopes'))->find($id); //查出红包模板让他的使用量加1
            $qy_send->number = $qy_send->number+1;
            $qy_send->save();
            //随机数组 金额
            if($_POST["radio"] == 2){
                $arrs = $this->demo($_POST["price"],$_POST["value"]);
                $arr = implode(",", $arrs);
            }else{
                $arrs = $this->getDivideNumber($_POST["price"],$_POST["value"]);
                $arr = implode(",", $arrs);
            }
            $h = Helper::getInstance();
            $selfurl = $h->get_http_server_name().'/Addons/Redenvelopes/H5/Replys/envelopes.html?id='.$id.'&corp_id='.$corp_id.'&agent_id='.$agent_id.'&send_id='.$send->id.'&money='.$arr;
            $im_url = $h->get_http_server_name()."/images/5a74fcc7f25ea9275760a94d849e68e.jpg"; //图片
            if($_POST["values"] == ""){
                $title =  "恭喜发财，大吉大利";
            }else{
                $title =  $_POST["values"];
            }
            $data = [
                'id'=>$send->id,
                'link_url' => $selfurl,
                'link_title' =>  $qy_send->qyname,
                'link_pic' => $im_url,
                'link_desc' => $title, 
            ];
            sendSuccess('获取成功',$data);
        }
    }


    public function envelopes(){
        $id = \Request::get('id');//模板id
        $money = \Request::get('money');
        $send_id = \Request::get('send_id');
        $corp_id = \Request::get('corp_id');
        $agent_id = \Request::get('agent_id');
        $send = (new Model("qy_envelopes_send"))->find($send_id);           //查出红包数据
        $qy_send = (new Model('qy_user_list'))->find($send->fs_user_id);   //查出发送红包者的数据
        $qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$corp_id]);
        $wid = $qyConfig->wid;
        // $replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid,'agent_id'=>$agent_id]);QyHelpers
        $replyConfig = QyHelpers::getInstance()->get_message_send_config($wid,$agent_id);
        if($_GET["code"]){
            $code = $_GET['code'];
            $app = QyWechatApi::getInstance()->get_qy_agent_app($corp_id,$replyConfig->agent_id,$replyConfig->secret);
            $accessToken = $app->access_token;
            $token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
            $resArr = json_decode(curlGet($url),1);
            $copyright = QyHelpers::copyright($wid);
            $user_id = $resArr['external_userid'];
            $OpenId = $resArr['OpenId'];
        }else{
            $redirect_uri = urlencode(Helper::getInstance()->get_http_server_name().'/Addons/Redenvelopes/H5/Replys/envelopes.html?corp_id='.$corp_id.'&agent_id='.$replyConfig->agent_id.'&send_id='.$send_id.'&id='.$id.'&money='.$money);
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$corp_id.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
            \Redirect::to($url);
        }
        $this->assign('copyright',$copyright);
        $this->assign('send',$send);
        $this->assign('send_id',$send_id);
        $this->assign('corp_id',$corp_id);
        $this->assign('id',$id);
        $this->assign('money',$money);
        $this->assign('user_id',$user_id);
        $this->assign('agent_id',$replyConfig->agent_id);
        $this->assign('OpenId',$OpenId);
        $this->assign('qy_send',$qy_send);
        return $this->show();
    }

    public function subhb(){
        header('Content-type:text/html; Charset=utf-8');
        setApi();
        $hb_id = $_POST['hb_id']; //红包id
        $may = $_POST['money']; //红包抢的随机红包值
        $moneys = explode(",",$may);
        $user_id = $_POST['user_id']; //用戶id
        $mb_id = $_POST['mb_id']; //模板id
        $openId = $_POST['OpenId']; //用户的OpenId
        $send = (new Model('qy_envelopes_send'))->find(["id"=>$hb_id]);
        $fs_user_id = (new Model('qy_user_list'))->find(["id"=>$send->fs_user_id]);
        $user = (new Model('qy_externalcontact_list'))->find(["external_userid"=>$user_id,"wid"=>$fs_user_id->wid]);
        if($user_id){
            $where['yh_id'] = $user->id;
            $where['hb_id'] = $hb_id;
        }else{
            $where['yh_id'] = $openId;
            $where['hb_id'] = $hb_id;
        }
        $yh_hb = (new Model('qy_envelopes_list'))->find($where);
        if(!$user_id && !$openId){
            sendError('不是企业客户');
        }
        if($yh_hb->id){
            sendError('您已领取过该红包了');
        }else{
            $envelopes_list = (new Model('qy_envelopes_list'))->where(["hb_id"=>$hb_id])->list_all();
            $count = count($envelopes_list);
            $money = $moneys[$count];
            $confing = (new Model('qy_envelopes_confing'))->find(["wid"=>$fs_user_id->wid,"type"=>1]);
            $appids = (new Model('qy_wechat_config'))->find(["wid"=>$fs_user_id->wid]);
            if(!$confing->id || $confing->status == 2){
                $pubs = (new Model('pubs'))->find($fs_user_id->wid);
                $users = (new Model('user'))->find($pubs->uid);
                if($users->balance < $money){
                    sendError("余额不足，请联系管理员充值");
                }
                $confing = (new Model('qy_envelopes_confing'))->find(["wid"=>$users->agid]);
                if(!$confing->id){
                    sendError("配置错误，请检查配置文件");
                }
            }
            $wid = $fs_user_id->wid;
            $mchid = $confing->mchid; 
            $appid = $appids->corp_id; 
            $appKey = $confing->appKey; 
            $apiKey = $confing->apiKey; 
            $wxPay = new WxpayService($mchid, $appid, $appKey, $apiKey, $wid);
            if (!$openId) exit('获取openid失败');
            $length = 20;
            $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            $len = strlen($str)-1;
            $randstr = '';
            for ($i=0;$i<$length;$i++) {
              $num=mt_rand(0,$len);
              $randstr .= $str[$num];
             }
            $outTradeNo = $randstr.$user->id; //订单号
            $payAmount = $money;  //转账金额，单位:元。转账最小金额为0.3元
            $trueName = $user->name;  //收款人真实姓名
            $result = $wxPay->createJsBizPackage($openId, $payAmount, $outTradeNo, $trueName);
            if($result == "true"){
                if($confing->type != 1){
                    $record = new Model("user_recharge_record");
                    $record->user_id = $users->id;
                    $record->openid = $users->id;
                    $record->money = $payAmount;
                    $record->recharge_time = time();
                    $record->out_trade_no = $outTradeNo;
                    $record->transaction_id = $outTradeNo;
                    $record->type = 2;
                    $record->status = 2;
                    $record->save();
                    // $users->balance = $users->balance - $payAmount;
                    // $users->save();
                }
                $mod = new Model('qy_envelopes_list');
                $mod->mb_id = $mb_id;
                $mod->hb_id = $hb_id;
                if($user_id){
                    $mod->yh_id = $user->id;
                }else{
                    $mod->yh_id = $openId;
                }
                $mod->price = $money;
                $mod->ctime = strtotime(date("Y-m-d H:i:s"));
                $mod->save();
                $send->sy_number = $send->sy_number-1;
                $send->save();
                if($mod->id){
                    sendSuccess('领取成功',$mod->id);
                }
            }else if($result["err_code"]){
                $err_code = (array)$result["err_code"];
                sendError('领取失败',$wxPay->transfers($err_code[0]));
            }else if($result["return_msg"]){
                $return_msg = (array)$result["return_msg"];
                sendError('领取失败',$return_msg[0]);
            }else{
                sendError('领取失败',$result);
            }
        }
    }

    public function check(){
        $id = \Request::get('id');//抢完红包后的整条记录
        $list = (new Model('qy_envelopes_list'))->find(["id"=>$id]);
        if(\Request::get('id')){  //当前用户抢红包的记录
            $hb_id = $list->hb_id;
        }
        if(\Request::get('send_id')){
            $hb_id = \Request::get('send_id');
        }   
        $send = (new Model('qy_envelopes_send'))->find(["id"=>$hb_id]);   //通过当前用户找到模板的数据
        $user = (new Model('qy_user_list'))->find(["id"=>$send->fs_user_id]);   //通过当前用户找到模板的数据

        $data = (new Model('qy_envelopes_list'))->where(["hb_id"=>$send->id,"mb_id"=>$send->mb_id])->list_all(); //查出与当前红包和模板对应的所有数据
        foreach($data as $key=>$value){
            $userlist = new Model('qy_externalcontact_list');
            $where['id'] = $value->yh_id;
            $data[$key]->user = $userlist->find($where);
            $maxs[] = $value->price;
        }
        $h = Helper::getInstance();
        $url = $h->get_http_server_name()."/images/5a74fcc7f25ea9275760a94d849e68e.jpg";
        $max = max($maxs);
        $this->assign("user",$user);
        $this->assign("max",$max);
        $this->assign("data",$data);
        $this->assign("list",$list);
        $this->assign("url",$url);
        $this->assign("send",$send);
        $this->assign("count",count($data));
        return $this->show();
    }

    public function demo($total,$num,$min = 0.3)
    {
        $overPlus = $total - $num * $min; // 剩余待发钱数
        $base = 0; // 总基数
        // 存放所有人数据
        $container = array();
        // 每个人保底
        for ($i = 0; $i < $num; $i++) {
            // 计算比重
            $weight = round(lcg_value() * 1000);
            $container[$i]['weight'] = $weight; // 权重
            $container[$i]['money'] = $min; // 最小值都塞进去
            $base += $weight; // 总基数
        }

        $len = $num - 1; // 下面要计算总人数-1的数据,
        for ($i = 0; $i < $len; $i++) {
            $money = floor($container[$i]['weight'] / $base * $overPlus * 100) / 100; // 向下取整,否则会超出
            $container[$i]['money'] += $money;
        }

        // 弹出最后一个元素
        array_pop($container);
        $result = array_column($container, 'money');
        $last_one = round($total - array_sum($result), 2);
        array_push($result, $last_one);
        return $result;
    }

    public function getDivideNumber($number, $total, $index = 2) {
        // 除法取平均数
        $divide_number  = bcdiv($number, $total, $index);
        // 减法获取最后一个数
        $last_number = bcsub($number, $divide_number*($total-1), $index);
        // 拼装平分后的数据返回
        $number_str = str_repeat($divide_number.'+', $total-1).$last_number;
        return explode('+', $number_str);
    }
}